package com.example.demo.controller;

import com.example.demo.common.ApplicationVariable;
import com.example.demo.common.ResultAjax;
import com.example.demo.common.SessionUtils;
import com.example.demo.model.Articleinfo;
import com.example.demo.model.ArticleinfoVO;
import com.example.demo.model.Userinfo;
import com.example.demo.model.UserinfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UesrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("/art")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private UesrService uesrService;

    private static final int DESC_LENGTh = 120;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    /**
     * 得到当前登录用户的文章列表页
     * @return
     */
    @RequestMapping("/mylist")
    public ResultAjax mylist(HttpServletRequest request) {
        // 1.得到当前登录用户
        Userinfo userinfo = SessionUtils.getUser(request);
        if (userinfo == null) {
            return ResultAjax.fail(-1,"请先登录");
        }
        // 2.根据用户id查询用户发表的文章
        List<Articleinfo> list = articleService.getListByUid(userinfo.getId());
        // 处理list 将正文变成简介
        if (list != null && list.size() > 0) {
            list.stream().parallel().forEach((art) -> {
                if (art.getContent().length() > 120) {
                    art.setContent(art.getContent().substring(0,DESC_LENGTh));
                }
            });

        }
        // 将结果返回给用户

        return ResultAjax.succ(list);
    }

    @RequestMapping("/del")
    public ResultAjax del (Integer aid , HttpServletRequest request) {
        // 文章删除
        // 1.参数校验
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"参数错误");
        }
        // 2.判断当前用户是否登录
        Userinfo userinfo = SessionUtils.getUser(request);
        if (userinfo == null) {
            return ResultAjax.fail(-2,"请先登录");
        }
        // 3.判断文章的归属人
        // 4.删除操作  3 + 4 在删除的时候顺边判断是不是归属人
        // delete from articleinfo where id = aid and uid = uid
        int result = articleService.del(aid , userinfo.getId());
        // 5.将结果返回给前端
        return ResultAjax.succ(result);
        // 3.删除文章
        // 4.返回数据给前端
    }

    @RequestMapping("/add")
    public ResultAjax add(ArticleinfoVO articleinfoVO, HttpServletRequest request) {
        // 2.参数校验
        if (articleinfoVO == null || !StringUtils.hasLength(articleinfoVO.getTitle()) || !StringUtils
                .hasLength(articleinfoVO.getContent())) {
            return ResultAjax.fail(-1,"参数错误");
        }
        // 1.判断用户是否登录
        Userinfo userinfo = SessionUtils.getUser(request);
        if (userinfo == null || userinfo.getId() <= 0) {
            return ResultAjax.fail(-2,"请先登录");
        }
        articleinfoVO.setUid(userinfo.getId());

        // 3.添加文章
        int result = articleService.add(articleinfoVO);
        // 4.将结果返回给后端
        return ResultAjax.succ(result);
    }

    @RequestMapping("/update_init")
    public ResultAjax update_init(Integer aid,HttpServletRequest request) {
        // 1.校验参数
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"参数错误");
        }
        // 2.判断用户是否登录 3.查询文章内容
        Userinfo userinfo    = (Userinfo) SessionUtils.getUser(request);
        if (userinfo == null || userinfo.getId() <= 0) {
            return ResultAjax.fail(-2,"请先登录");
        }
        Articleinfo result = articleService.getArticleByUid(aid,userinfo.getId());
        // 4.将文章内容提交给前端
        return ResultAjax.succ(result);
    }

    @RequestMapping("update_sub")
    public ResultAjax update_sub(Articleinfo articleinfo,HttpServletRequest request) {
        // 不要判断登录,初始化的时候判断过了
        // 1.参数校验
        if (articleinfo == null ||
        !StringUtils.hasLength(articleinfo.getTitle()) ||
        !StringUtils.hasLength(articleinfo.getContent()) ||
        articleinfo.getId() == 0) {
            return ResultAjax.fail(-1,"参数错误");
        }
        // 2.获取登录用户
        Userinfo userinfo = SessionUtils.getUser(request);
        if (userinfo == null ) {
            return ResultAjax.fail(-2,"请先登录");
        }
        articleinfo.setUid(userinfo.getId()); // 给文章设置当前用户id
        articleinfo.setUpdatetime(LocalDateTime.now());
        // 3.修改文章内容并且校验归属人
        int result = articleService.update_sub(articleinfo);
        // 4.将修改后的结果返回给后端
        return ResultAjax.succ(result);
    }


    @RequestMapping("detail")
    public ResultAjax detail(Integer aid) throws ExecutionException, InterruptedException {
        // 1.参数校验
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"非法参数");
        }
        // 2.查询文章详情 得到uid
        Articleinfo articleinfo = articleService.getArtById(aid);
        if (articleinfo == null || articleinfo.getId() <= 0) {
            return ResultAjax.fail(-1,"非法参数");
        }
        // 3.根据uid查询用户的详情信息 34线程池并发
        // 4.根据uid查询用户发表的总文章数
        FutureTask<UserinfoVO> userTask = new FutureTask(()->{
            UserinfoVO userinfoVO= uesrService.getuserById(articleinfo.getUid());
            return userinfoVO;
        });
        taskExecutor.submit(userTask);
        FutureTask<Integer> artCountTask = new FutureTask<>(()-> {
           return articleService.getArtCOuntByUId(articleinfo.getUid());
        });
        taskExecutor.submit(artCountTask);

        // 5.组装数据,返回结果给前端
        UserinfoVO userinfoVO = userTask.get();
        int artCount = artCountTask.get();
        userinfoVO.setArtCount(artCount);
        HashMap<String, Object> result = new HashMap<>();
        result.put("user",userinfoVO);
        result.put("art",articleinfo);
        return ResultAjax.succ(result);
    }

    @RequestMapping("updatercount")
    public ResultAjax updateRcount(Integer aid) {
        // 参数校验
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"参数错误");
        }
        // 对文章阅读量进行修改
        int result = articleService.updateRcount(aid);
        // 返回数据给前端
        return ResultAjax.succ(result);
    }

    /**
     * 查询分页功能
     */
    @RequestMapping("/getlistbypage")
    public ResultAjax getListByPage(Integer pszie ,Integer pindex) throws ExecutionException, InterruptedException {
        // 1.加工参数 参数矫正
        if (pindex == null || pindex < 1) {
            pindex = 1;
        }
        if (pszie == null || pszie < 1) {
            pszie = 2;
        }
        // 2.查询操作 并发编程 页码分页信息 总共多少页-- 总条数除以 psize 向上取整
        Integer finalPszie = pszie;
        Integer finalPindex = pindex;
        FutureTask<List<Articleinfo>> listTask =
                new FutureTask<>(()->{
                    // 计算好传递给数据库 否则索引失效
                    int offset = finalPszie * (finalPindex - 1);
                    return articleService.getListByPage(finalPszie,offset);
                });


        FutureTask<Integer> sizeTask = new FutureTask<>(()->{

            int totalCount = articleService.getArtCount();
            double sizeTemp = totalCount * 1.0 / finalPszie;
            int size = (int)Math.ceil((sizeTemp));
            return size;
        });
        taskExecutor.submit(listTask);
        taskExecutor.submit(sizeTask);
        List<Articleinfo> list = listTask.get();
        int size = sizeTask.get();

        // 3. 组装数据
        HashMap<String , Object> map = new HashMap<>();
        map.put("list",list);
        map.put("size",size);
        // 4. 将结果返回1给前端
        return ResultAjax.succ(map);
    }
}
